package com.runshu.newsmartark.activity;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.naz.serial.port.ModuleManager;
import com.naz.serial.port.SerialPort;
import com.open.hule.library.entity.AppUpdate;
import com.open.hule.library.utils.UpdateManager;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.base.BaseActivity;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.entity.ApkVersionEntity;
import com.runshu.newsmartark.entity.HwInfo;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.entity.WeatherEntity;
import com.runshu.newsmartark.event.BindEventBus;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.contract.GetVersionContract;
import com.runshu.newsmartark.mvp.contract.HwHeartContract;
import com.runshu.newsmartark.mvp.contract.MainHomeContract;
import com.runshu.newsmartark.mvp.contract.ReadCardContract;
import com.runshu.newsmartark.mvp.model.GetVersionModel;
import com.runshu.newsmartark.mvp.model.HwHeartModel;
import com.runshu.newsmartark.mvp.model.MainHomeModel;
import com.runshu.newsmartark.mvp.model.ReadCardModel;
import com.runshu.newsmartark.mvp.presenter.GetVersionPresenter;
import com.runshu.newsmartark.mvp.presenter.HwHeartPresenter;
import com.runshu.newsmartark.mvp.presenter.MainHomePresenter;
import com.runshu.newsmartark.mvp.presenter.ReadCardPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.reader.base.ReaderBase;
import com.runshu.newsmartark.reader.helper.ReaderHelper;
import com.runshu.newsmartark.reader.helper.ReaderSetting;
import com.runshu.newsmartark.util.Beeper;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.StringUtils;
import com.runshu.newsmartark.util.ToolScanner;
import com.runshu.newsmartark.util.UserCardUtil;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.CommonShowDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;

import static com.runshu.newsmartark.common.ConstantUrl.Share_StockNum;
import static com.runshu.newsmartark.common.ConstantUrl.Share_isAdmin;

@BindEventBus
public class YinKouMainActivity extends BaseActivity implements MainHomeContract.View, GetVersionContract.View, HwHeartContract.View, ToolScanner.OnScanSuccessListener, ReadCardContract.View {
    private static final String TAG = "MainActivity";
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.img_weather)
    ImageView mImgWeather;
    @BindView(R.id.tv_wendu)
    TextView mTvWendu;
    @BindView(R.id.tv_info)
    TextView mTvInfo;
    @BindView(R.id.rela_info)
    RelativeLayout mRelaInfo;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.rela_exit)
    RelativeLayout mRelaExit;
    @BindView(R.id.tv_stock_num)
    TextView mTvStockNum;
    @BindView(R.id.tv_hint_opean)
    TextView mTvHintOpean;
    @BindView(R.id.rela_opean_door)
    RelativeLayout mRelaOpeanDoor;
    @BindView(R.id.tv_hint_manager)
    TextView mTvHintManager;
    @BindView(R.id.rela_manager_door)
    RelativeLayout mRelaManagerDoor;
    @BindView(R.id.img_phone)
    ImageView mImgPhone;
    @BindView(R.id.tv_mac_rigth)
    TextView mTvMacRigth;
    @BindView(R.id.tv_mac_left)
    TextView mTvMacLeft;
    @BindView(R.id.tv_exit)
    TextView mTvExit;
    @BindView(R.id.tv_time)
    TextClock mTvTime;
    @BindView(R.id.tv_search_all)
    TextView mTvSearchAll;
    @BindView(R.id.rela_search_pro)
    RelativeLayout mRelaSearchPro;
    private CommonShowDialog commonShowDialog;
    private final String macAddress = MacUtils.getFormatMacAddr();  //"EA06GC27A573";
    private MainHomePresenter homePresenter;
    private GetVersionPresenter versionPresenter;
    private HwHeartPresenter heartPresenter;
    private CountDownTimer timerDialog;
    private CountDownTimer timerExit;
    public static SerialPort mSerialPort = null;
    private ReaderHelper mReaderHelper;
    private ReaderBase readerBase;
    private static ReaderSetting m_curReaderSetting;
    final static int COUNTS = 5;//点击次数
    final static long DURATION = 3 * 1000;//规定有效时间
    long[] mHits = new long[COUNTS];

    private ReadCardPresenter readCardPresenter;
    private ToolScanner toolScanner;
    private LocalBroadcastManager lbm;
    IntentFilter itent;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        lbm = LocalBroadcastManager.getInstance(this);
        itent = new IntentFilter();
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_READER_SETTING);
        toolScanner = new ToolScanner(this);
        readCardPresenter = new ReadCardPresenter(this, new ReadCardModel());
        heartPresenter = new HwHeartPresenter(this, new HwHeartModel());
        homePresenter = new MainHomePresenter(this, new MainHomeModel());
        versionPresenter = new GetVersionPresenter(this, new GetVersionModel());
        mTvMacRigth.setText(macAddress);
        mTvDate.setText(StringUtils.getYearMonthHourMinuteTimeChinese(Calendar.getInstance().getTimeInMillis()) + " " + StringUtils.getTodayStringWeek());
    }

    @Override
    protected void initData() {
        try {
            mSerialPort = new SerialPort(new File(ConstantUrl.Share_takeStockPartPort), 115200, 0);
            ModuleManager.newInstance().setUHFStatus(true);
            mReaderHelper = ReaderHelper.getDefaultHelper();
            try {
                mReaderHelper.setReader(mSerialPort.getInputStream(), mSerialPort.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
            readerBase = mReaderHelper.getReader();
            m_curReaderSetting = mReaderHelper.getCurReaderSetting();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void bindListener() {
        mTvTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int min = cal.get(Calendar.MINUTE);
                if (min == 0 || min == 30) {
                    LogUtil.e(TAG, "现在是北京时间" + hour + ":" + min);
                    homePresenter.getWeath(macAddress);
                    heartPresenter.sendHwHeart(macAddress);
                    homePresenter.getIndexCount(macAddress);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (timerExit != null) {
            timerExit.cancel();
        }
        if (hasAuth()) {
            mRelaExit.setVisibility(View.VISIBLE);
            countDownExit();
        } else {
            mRelaExit.setVisibility(View.GONE);
        }
        //清除管理模式
        SharedPreferencesUtils.remove(context, Share_isAdmin);
        heartPresenter.sendHwHeart(macAddress);
        homePresenter.getWeath(macAddress);
        homePresenter.getIndexCount(macAddress);
        versionPresenter.getVersionInfo(macAddress, String.valueOf(MacUtils.getLocalVersion(context)));
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }


    private void showExitDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("已安全退出");
        commonShowDialog.setContentHint("欢迎下次使用");
        commonShowDialog.setImgShow(R.mipmap.icon_dia_exit);
        commonShowDialog.show();
        countDownShowDia();

    }

    @OnClick({R.id.tv_mac_rigth, R.id.rela_search_pro, R.id.rela_exit, R.id.rela_opean_door, R.id.rela_manager_door, R.id.tv_exit})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.rela_opean_door:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                if (hasAuth()) {
                    connect();
                } else {
//                    intent.setClass(context, LoginActivity.class);
//                    startActivity(intent);
                    SoundPoolUtils.play(context, R.raw.raw_face, 0);
                    intent.setClass(context, RegisterAndRecognizeActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.rela_manager_door:
                if (hasAuth()) {
                    if (MyApplication.getUserInfoGlob().isAdmin()) {
                        if (timerExit != null) {
                            timerExit.cancel();
                        }
                        intent.setClass(context, ManagerActivity.class);
                        startActivity(intent);
                    } else {
                        showNotAdiminDia();
                    }
                } else {
                    //设置管理模式
                    setisAdmin();
//                    intent.setClass(context, LoginActivity.class);
//                    startActivity(intent);
                    SoundPoolUtils.play(context, R.raw.raw_face, 0);
                    intent.setClass(context, RegisterAndRecognizeActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tv_exit:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                mRelaExit.setVisibility(View.GONE);
                exitLogin();
                showExitDia();
                break;
            case R.id.rela_search_pro:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                intent = new Intent(context, NewProDtaActivity.class);
                startActivity(intent);
                break;

            case R.id.tv_mac_rigth:
                exitAfterMany();
                break;
        }
    }

    @Override
    public void getWeather(ResponseBean responseBean) {
        WeatherEntity weatherEntity = (WeatherEntity) responseBean.pullData();
        if (weatherEntity == null)
            return;
        if ("1".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_qing);
        } else if ("2".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_duoyun);
        } else if ("3".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_yin);
        } else if ("4".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_xiayu);
        } else if ("5".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_xue);
        } else if ("6".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_wu);
        } else if ("7".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_scb);
        } else if ("8".equals(weatherEntity.getType())) {
            mImgWeather.setImageResource(R.mipmap.icon_weather_mai);
        } else {
            mImgWeather.setImageResource(R.mipmap.icon_weather_duoyun);
        }

        mTvDate.setText(weatherEntity.getDate() + "  " + weatherEntity.getWeek());
        mTvInfo.setText(weatherEntity.getCity() + "  " + weatherEntity.getWeather());
        mTvWendu.setText(weatherEntity.getTemperature());


    }

    @Override
    public void getIndexCount(ResponseBean responseBean) {

        HwInfo hwInfo = (HwInfo) responseBean.pullData();
        mTvSearchAll.setText(Html.fromHtml("总库存共 " + "<font color=\"#FFB000\">" + hwInfo.getAllHwInHospitalStock() + "</font>" + " 件耗材，点击查询..."));
        mTvStockNum.setText(hwInfo.getLocalHwStock());
        SharedPreferencesUtils.put(context, Share_StockNum, hwInfo.getLocalHwStock());
    }

    @Override
    public void OnGetVersionInfoSuccess(ResponseBean responseBean) {
        ApkVersionEntity versionEntity = (ApkVersionEntity) responseBean.pullData();
        if (versionEntity == null)
            return;
        int version_code = versionEntity.getVersion_code();
        if (MacUtils.getLocalVersion(context) < version_code) {
            getVersion(versionEntity.getVersion_url(), versionEntity.getMessage(), versionEntity.getVersion_code(), versionEntity.isForcible());
        }
    }

    @Override
    public void OnSendHwHeartSuccess(ResponseBean responseBean) {

    }

    @Override
    public void verifyIcCardSuccess(ResponseBean responseBean) {
        if (timerExit != null) {
            timerExit.cancel();
        }
        UserInfoEntity userInfoEntity = (UserInfoEntity) responseBean.pullData();
        MyApplication.application.setUserInfoEntity(userInfoEntity);
        loginSuccess();
        connect();

//        goTakeStock(context);
    }

    @Override
    public void onError(String msg) {
        ToastUtils.showText(msg);
    }

    /**
     * @author yu
     * @time 2020/6/28  10:25 AM
     * @decs：版本更新
     */
    private void getVersion(String url, String updateInfo, int code, boolean force) {
        AppUpdate appUpdate = new AppUpdate.Builder()
                //更新地址（必传）
                .newVersionUrl(url)
                // 版本号（非必填）
                .newVersionCode(String.valueOf(code))
                // 通过传入资源id来自定义更新对话框，注意取消更新的id要定义为btnUpdateLater，立即更新的id要定义为btnUpdateNow（非必填）
                .updateResourceId(R.layout.dialog_update)
                // 更新的标题，弹框的标题（非必填，默认为应用更新）
                .updateTitle(R.string.update_title)
                // 更新内容的提示语，内容的标题（非必填，默认为更新内容）
                .updateContentTitle(R.string.update_content_lb)
                // 更新内容（非必填，默认“1.用户体验优化\n2.部分问题修复”）
                .updateInfo(updateInfo)
                // 文件大小（非必填）
                // 保存文件路径（默认前缀：Android/data/包名/files/ 文件名：download）
//                .savePath("/A/B")
                //是否采取静默下载模式（非必填，只显示更新提示，后台下载完自动弹出安装界面），否则，显示下载进度，显示下载失败
                .isSilentMode(false)
                //是否强制更新（非必填，默认不采取强制更新，否则，不更新无法使用）
                .forceUpdate(force ? 1 : 0)
                .build();
        new UpdateManager().startUpdate(YinKouMainActivity.this, appUpdate);
    }

    private void showNotAdiminDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("您没有管理权限 ，请联系管理员！");
        commonShowDialog.setImgShow(R.mipmap.icon_exit_warn);
        commonShowDialog.show();
        countDownShowDia();
    }

    /**
     * 倒计时显示Dialog
     */
    private void countDownShowDia() {
        timerDialog = new CountDownTimer(2000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                commonShowDialog.dismiss();
                timerDialog.cancel();
            }
        }.start();
    }


    /**
     * 倒计时显示退出
     */
    @SuppressLint("SetTextI18n")
    private void countDownExit() {
        mRelaExit.setVisibility(View.VISIBLE);
        mTvName.setText("Hi，" + MyApplication.getUserInfoGlob().getUsername());
        timerExit = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTvExit.setText("安全退出  " + millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                mRelaExit.setVisibility(View.GONE);
                exitLogin();
                showExitDia();

            }
        }.start();
    }

    private void connect() {
        //开灯
        readerBase.writeGpioValue(m_curReaderSetting.btReadId, (byte) 0x04, (byte) 0x01);
        //开门
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                readerBase.writeGpioValue(m_curReaderSetting.btReadId, (byte) 0x03, (byte) 0x01);
                goTakeStock(context);
            }
        }, 100);
    }


    /**
     * 连续点击多次退出
     */
    private void exitAfterMany() {
        /**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         */
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//System.currentTimeMillis()

        if ((mHits[mHits.length - 1] - mHits[0] <= DURATION)) {
            String tips = "您已在[" + DURATION + "]ms内连续点击【" + mHits.length + "】次了！！！";
            Toast.makeText(YinKouMainActivity.this, tips, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            toolScanner.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        LogUtil.e(TAG, "退出程序!!!!!!");
        if (mSerialPort != null) {
            mSerialPort.close();
        }
        if (timerExit != null) {
            timerExit.cancel();
        }
        if (timerDialog != null) {
            timerDialog.cancel();
        }
        //释放读写器上电掉电控制设备
        ModuleManager.newInstance().setUHFStatus(false);
        Beeper.release();
        exitLogin();
        super.onDestroy();
    }


    @Override
    public void onScanSuccess(String barcode) {
        String s = UserCardUtil.decimal2Hex(barcode);
        String s1 = UserCardUtil.reverseCardId(s);
        LogUtil.e("卡号：", barcode + " 转换后===" + s+"翻转==="+s1);
        //验证成功
        readCardPresenter.verifyIcCard(s1);
    }

    private void goTakeStock(Context context) {
        Intent intents = new Intent(context, TakeStockDtaActivity.class);
        startActivity(intents);
    }

    //event 没有管理权限
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddClientEvent(Event event) {
        if (event.getCode() == EventCode.EventNOTADMIN) {
            showNotAdiminDia();
        }
    }

}